package com.qyhl.shop.shop.center.coupon.detail;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.dialog.CommonDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopCouponBean;
import com.qyhl.webtv.module_user.share.UserShareUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_CENTER_COUPON_DETAIL)
public class ShopCenterCouponDetailActivity extends BaseActivity implements ShopCenterCouponDetailContract.ShopCenterCouponDetailView {
    @BindView(R2.id.shop_cover)
    RoundedImageView shopCover;
    @BindView(R2.id.shop_name)
    TextView shopName;
    @BindView(R2.id.date)
    TextView date;
    @BindView(R2.id.shop_address)
    TextView shopAddress;
    @BindView(R2.id.tag)
    ImageView tag;
    @BindView(R2.id.code)
    TextView code;
    @BindView(R2.id.qr_code)
    ImageView qrCode;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.coupon_rule)
    TextView couponRule;

    private ShopCenterCouponDetailPresenter mPresenter;

    @Autowired(name = "couponId")
    int couponId;

    private ShopCouponBean mBean;


    @Override
    protected int getContentView() {
        return R.layout.shop_activity_center_coupon_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        mPresenter = new ShopCenterCouponDetailPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        mPresenter.getDetail(CommonUtils.getInstance().getUserName(), couponId);
    }

    @Override
    protected void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDetail(CommonUtils.getInstance().getUserName(), couponId);
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(CommonUtils.getInstance().getUserName(), couponId);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShopCouponBean bean) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        mBean = bean;

        shopName.setText(bean.getShopName());

        Glide.with(ShopCenterCouponDetailActivity.this)
                .load(bean.getShopImageUrl())
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(shopCover);

        date.setText("有效期：" + bean.getBeginDate() + " ~ " + bean.getEndDate());

        shopAddress.setText(bean.getAddress());

        code.setText(bean.getQrcode());

        couponRule.setText(bean.getDetail());

        if (bean.isExpire() || bean.isUsed()) {
            code.setTextColor(getResources().getColor(R.color.shop_common_message));
            code.setBackgroundResource(R.color.global_background);
            UserShareUtil shareUtil = new UserShareUtil(this, 265, bean.getQrcode(), qrCode, true);
        } else {
            code.setTextColor(getResources().getColor(R.color.shop_common_red));
            code.setBackgroundResource(R.color.shop_coupon_code_bg_on);
            UserShareUtil shareUtil = new UserShareUtil(this, 265, bean.getQrcode(), qrCode);
        }

        if (bean.isUsed()) {
            tag.setVisibility(View.VISIBLE);
            tag.setImageResource(R.drawable.shop_coupon_detail_used_icon);
        } else if (bean.isExpire()) {
            tag.setVisibility(View.VISIBLE);
            tag.setImageResource(R.drawable.shop_coupon_detail_exceed_icon);
        } else {
            tag.setVisibility(View.GONE);
        }


    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~");
    }


    @OnClick({R2.id.back_btn, R2.id.shop_contact, R2.id.shop_address})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.shop_contact) {
            MPermissionUtils.requestPermissionsResult(ShopCenterCouponDetailActivity.this, 11, new String[]{Manifest.permission.CALL_PHONE}, new MPermissionUtils.OnPermissionListener() {
                @Override
                public void onPermissionGranted() {
                    new CommonDialog.Builder(ShopCenterCouponDetailActivity.this)
                            .setTitle("提示", R.color.global_black_lv1)
                            .setMessage("是否要拨打商铺电话？", R.color.global_black_lv2)
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mBean.getPhone()));
                                    startActivity(intent);
                                }
                            }, R.color.global_base)
                            .setNegativeButton("取消", null, R.color.global_gray_lv2).show();
                }

                @Override
                public void onPermissionDenied() {
                    MPermissionUtils.showTipsDialog(ShopCenterCouponDetailActivity.this);
                }
            });
        } else if (viewId == R.id.shop_address) {
            try {
                new CommonDialog.Builder(ShopCenterCouponDetailActivity.this)
                        .setTitle("提示", R.color.global_black_lv1)
                        .setMessage("是否要跳转至高德地图，进行导航？", R.color.global_black_lv2)
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                goNaviByGaoDeMap(mBean.getLatitude(), mBean.getLongitude());
                            }
                        }, R.color.global_base)
                        .setNegativeButton("取消", null, R.color.global_gray_lv2).show();

            } catch (ActivityNotFoundException e) {
                showToast("请安装高德地图！");
            }
        }
    }

    /* func:调起高德导航
     * @param lat 纬度
     * @param lon 经度
     * @param dev 是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
     * @param t  t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     */
    private void goNaviByGaoDeMap(Double lat, Double lon) throws ActivityNotFoundException {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //将功能Scheme以URI的方式传入data
        Uri uri = Uri.parse("amapuri://route/plan/" +
                "?sourceApplication=" + ShopCenterCouponDetailActivity.this.getString(R.string.app_name)
                + "&dlat=" + lat
                + "&dlon=" + lon
                + "&dev=0"
                + "&t=0");
        intent.setData(uri);
        intent.setPackage("com.autonavi.minimap");
        ShopCenterCouponDetailActivity.this.startActivity(intent);
    }
}
